package com.zhongketech.sunflower.receiver;

import com.zhongketech.sunflower.MyApplication;
import com.zhongketech.sunflower.database.Data;
import com.zhongketech.sunflower.database.PhoneNumberData;
import com.zhongketech.sunflower.filter.PhoneManager;
import com.zhongketech.sunflower.util.Constants;
import com.zhongketech.sunflower.util.Utilities;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;


public class PhoneStatReceiver extends BroadcastReceiver{

	private static final String TAG = "PhoneStatReceiver";

	private static boolean incomingFlag = false;

	private static String incoming_number = null;

	@Override
	public void onReceive(Context context, Intent intent)
	{
		//如果是拨打电话
		if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL))
		{                        
			incomingFlag = false;
			String phoneNumber = Utilities.replace(intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));        
			Utilities.logCat(TAG, "call OUT:"+phoneNumber,Constants.LOG_INFO);
			//PhoneManager.endCallRoot();
			if(Data.getinstance().isExit(new PhoneNumberData(phoneNumber, null)))
			{
				Toast.makeText(context, "禁止拨打此电话",
						Toast.LENGTH_SHORT).show();
				setResultData(null);	
			}

		}
		else
		{                        
			//如果是来电
			TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);                        

			switch (tm.getCallState()) 
			{
			case TelephonyManager.CALL_STATE_RINGING:
				incomingFlag = true;//标识当前是来电
				incoming_number = Utilities.replace(intent.getStringExtra("incoming_number"));
				Utilities.logCat(TAG, "RINGING :"+ incoming_number,Constants.LOG_INFO);

				if(Data.getinstance().isExit(new PhoneNumberData(incoming_number, null)))
				{
					PhoneManager.endCall(context);
				}

				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:                                
				if(incomingFlag)
				{
					Utilities.logCat(TAG, "incoming ACCEPT :"+ incoming_number,Constants.LOG_INFO);
				}
				break;
			case TelephonyManager.CALL_STATE_IDLE:                                
				if(incomingFlag)
				{
					Utilities.logCat(TAG, "incoming IDLE",Constants.LOG_INFO);                                
				}
				break;
			} 
		}
	}


}
